package cn.tedu.baking.filter;

import cn.tedu.baking.pojo.entity.User;
import cn.tedu.baking.pojo.ov.UserVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器类
 *
 * @WebFilter 标记当前类是一个过滤器类
 * filterName = "loginFilter" 设置过滤器的名字
 * urlPatterns = "/admin.html" 指定过滤器拦截的路径
 */
@WebFilter(filterName = "loginFilter", urlPatterns = "/")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse
            servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行了~");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
//将ServletResponse强转为HttpServletResponse
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//获取本次会话中的session对象
        HttpSession session = request.getSession();
//获取session中存储的用户信息
        UserVO user = (UserVO) session.getAttribute("user");
//判断user中是否存储了用户信息
        if (user == null) {
//如果用户信息为null,说明用户没有登陆过,跳转到登录界面
//发送响应信息,告知浏览器,接下来要访问的资源的路径
            response.sendRedirect("/login.html");
            return;
        }
//本身存储了用户信息,说明用户已经登录成功了,那么可以直接访问目标资源
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
